package com.macrounion.atv.listener;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.macrounion.atv.cache.ChannelCache;
import com.macrounion.atv.processor.ChannelProcessor;
import com.macrounion.atv.processor.CurrentDataProcessor;
import com.macrounion.atv.service.entity.Channel;
import com.macrounion.atv.service.entity.CurrentData;
import com.macrounion.atv.service.entity.ProtocolC;
import com.macrounion.atv.service.entity.ext.DeviceExt;

@Component
public class RePingGetDeviceDataListener{

	@Autowired
	private CurrentDataProcessor currentDataProcessor;
	@Autowired
	private ChannelCache channelCache;
	@Autowired
	private ChannelProcessor channelProcessor;
	
	public void receive(DeviceExt device, List<CurrentData> datas,Map<String,ProtocolC> protocolcMap) {
		List<CurrentData> resp = Lists.newArrayList();
		datas.forEach(d->{
			CurrentData data = new CurrentData();
			ProtocolC pc = protocolcMap.get(d.getChannelCode());
			if(pc != null & device!=null) {
				data.setChannelCode(pc.getChannelCode());
				Channel c = channelCache.getChannel(device.getId(), pc.getChannelCode());
				if(c!=null) {
					data.setId(UUID.randomUUID().toString());
					data.setChannelId(c.getId());
					data.setCreatedTime(new Date());
					data.setDeviceCode(device.getDeviceCode());
					data.setDeviceId(device.getId());
					data.setShowValue(channelProcessor.getVaule(c,d.getValues()));
					data.setSpotId(device.getSpotId());
					data.setUnit(c.getUnit());
					data.setValues(d.getValues());
					Integer ala = channelProcessor.getAlarm(c,data.getShowValue());
					data.setAlarm(ala);
					channelProcessor.sendAlarmToItu(device,c,data);
					resp.add(data);
				}
			}
		});
		//存储数据
		if(device!=null&&!StringUtils.isEmpty(device.getId())) {
			currentDataProcessor.saveDataFromSnmp(device.getId(),resp,"curdata");
		}
			
	}

}
